package extract;

import control.CConnection;
import control.CRegion;
import model.Region;
import java.util.StringTokenizer;
import java.util.Random;
import java.io.*;
import java.sql.*;

public class ExtractRegion {
	public static void main(String args[]) {
		CConnection cn = new CConnection();
		int northRegion[] = {1,3,4,14,22,23,27},
		    northeastRegion[] = {2,5,6,10,15,17,18,20,26},
		    centerRegion[] = {7,9,11,12},
		    southeastRegion[] = {8,13,19,25},
		    southRegion[] = {16,21,24};
		
		try {
			cn.createConnection();
			CRegion cr = new CRegion(cn);
			Random rand = new Random();
			
			BufferedReader input = new BufferedReader(new FileReader("data/brazilianForests.txt"));
			String line;

			for(int i = 1; (line = input.readLine()) != null; i++) {
				StringTokenizer st = new StringTokenizer(line, ";");
				Region r = new Region();
				
				r.setRegionID(i);
				r.setDescription(st.nextToken());
				int aux = Integer.parseInt(st.nextToken());
				
				if (!st.hasMoreTokens()) {
					switch (aux) {
						case 1:
							r.setStateID(northRegion[rand.nextInt(northRegion.length)]);
							break;
						case 2:
							r.setStateID(northeastRegion[rand.nextInt(northeastRegion.length)]);
							break;
						case 3: 
							r.setStateID(centerRegion[rand.nextInt(centerRegion.length)]);
							break;
						case 4:
							r.setStateID(southeastRegion[rand.nextInt(southeastRegion.length)]);
							break;
						case 5:
							r.setStateID(southRegion[rand.nextInt(southRegion.length)]);
							break;
						default: 
							r.setStateID(1);
							break;
					}		 
				}
				else {
					r.setStateID(Integer.parseInt(st.nextToken()));
				}
				
				cr.create(r);
			}
			
			System.out.println("Regions added successfully.");
		}
		catch (ClassNotFoundException e) {
			System.err.println("Couldn't connect to Derby Database.");
		}
		catch (SQLException e) {
			System.err.println("Error in SQL Statement.");
		}
		catch (FileNotFoundException e) {
			System.err.println("File not found!");
		}
		catch (IOException e) {}
	}
}